<template>
    <v-container class="justify-start full-height">
        <p class="title white--text">设置</p>
        <v-list
                subheader
                two-line
        >
            <v-subheader>基础信息</v-subheader>
            <v-list-item>
                <v-list-item-content>
                    <v-list-item-title>Device Number（设备号）</v-list-item-title>
                    <v-list-item-subtitle>{{ machineIdSync }}
                    </v-list-item-subtitle>
                </v-list-item-content>
            </v-list-item>
        </v-list>
        <v-list
                subheader
                two-line
                class="mt-3"
        >
            <v-subheader>管理员设置</v-subheader>
            <v-list-item to="/setting/operation-record">
                <v-list-item-content>
                    <v-list-item-title>Operation record（录入操作记录）</v-list-item-title>
                    <v-list-item-subtitle>Entering printer operation record.
                    </v-list-item-subtitle>
                </v-list-item-content>
            </v-list-item>
            <v-list-item to="/setting/declare">
                <v-list-item-content>
                    <v-list-item-title>Failure declaration（故障申报）</v-list-item-title>
                    <v-list-item-subtitle>Entering failure to declare.</v-list-item-subtitle>
                </v-list-item-content>
            </v-list-item>
<!--            <v-list-item to="/setting/password">-->
<!--                <v-list-item-content>-->
<!--                    <v-list-item-title>Password（修改密码）</v-list-item-title>-->
<!--                    <v-list-item-subtitle>Require password for purchase or use password to restrict purchase-->
<!--                    </v-list-item-subtitle>-->
<!--                </v-list-item-content>-->
<!--            </v-list-item>-->
            <v-list-item @click="checkForUpdate">
                <v-list-item-content>
                    <v-list-item-title>ReleaseNotes（检查更新）</v-list-item-title>
                    <v-list-item-subtitle>Check for new versions and update them automatically.
                    </v-list-item-subtitle>
                </v-list-item-content>
            </v-list-item>
        </v-list>
        <v-list class="mt-3">
            <v-subheader>系统设置</v-subheader>
            <v-list-item>
                <v-list-item-action>
                    <v-checkbox v-model="autoStart"></v-checkbox>
                </v-list-item-action>
                <v-list-item-content>
                    <v-list-item-title>Auto Start（开机自启）</v-list-item-title>
                    <v-list-item-subtitle>Setting boot automatically</v-list-item-subtitle>
                </v-list-item-content>
            </v-list-item>
        </v-list>
        <v-flex>
            <v-dialog v-model="hasNewVersion" persistent max-width="300">
                <v-card :loading="downloading">
                    <template slot="progress">
                        <v-progress-linear
                                v-model="downloadPercent"
                        ></v-progress-linear>
                    </template>
                    <v-card-title>发现新版本</v-card-title>
                    <v-card-text>
                        {{ remark }}
                    </v-card-text>
                    <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn color="secondary" text @click="hasNewVersion = false">取消</v-btn>
                        <v-btn v-show="hasNewVersion && !dialogUpdateNow" color="info" text @click="downloadAndUpdate()">{{downloading ? '正在下载中..........' : '立即下载'}}</v-btn>
                        <v-btn v-show="dialogUpdateNow" color="info" text @click="updateNow()">安装包已下载，立即更新吗？</v-btn>
                    </v-card-actions>
                </v-card>
            </v-dialog>
        </v-flex>
        <v-snackbar
                v-model="showError"
                color="accent"
        >
            {{ errorInfo }}
            <v-btn
                    color="info"
                    text
                    @click="showError = false"
            >
                <v-icon small color="red">mdi-close</v-icon>
            </v-btn>
        </v-snackbar>
    </v-container>
</template>

<script>
    import {ipcRenderer} from 'electron'
    import {getStore} from "../../utils/storage";
    import {machineIdSync} from 'node-machine-id';

    export default {
        name: "setting",
        data: () => ({
            autoStart: false,
            versionInfoList: [],
            errorInfo: {},
            remark: '性能优化，修复部分网络卡顿问题',
            showError: false,
            hasNewVersion: false,
            downloading: false,
            dialogUpdateNow: false,
            downloadPercent: 0,
            machineIdSync: machineIdSync()
        }),

        mounted() {
            this.getAutoStartValue();
            this.versionInfoList = this.getVersionInfoList();
            this.checkForUpdate();
        },
        destroyed() {
            // 移除事件监听
            ipcRenderer.removeAllListeners('updateMessage');
            ipcRenderer.removeAllListeners('downloadProgress');
            ipcRenderer.removeAllListeners('isUpdateNow');
        },
        methods: {
            getVersionInfoList() {
                return getStore('versionInfoList') && getStore('versionInfoList').length <= 0 ? [] : getStore('versionInfoList')
            },
            changeAutoStart() {
                if (this.autoStart) {
                    this.enableAutoStart()
                } else {
                    this.disableAutoStart()
                }
            },
            getAutoStartValue() {
                // 检查是否自动启动
                ipcRenderer.send('getAutoStartValue')
                ipcRenderer.on('getAutoStartValue', (event, result) => {
                    this.autoStart = result;
                    // 首次不watch对象
                    this.$watch('autoStart', this.changeAutoStart)
                })
            },
            enableAutoStart() {
                // 设置自动启动
                ipcRenderer.send('enableAutoStart')
            },
            disableAutoStart() {
                // 取消自动启动
                ipcRenderer.send('disableAutoStart')
            },
            downloadAndUpdate() {
                this.downloading = true;
                // 开始下载
                ipcRenderer.send('downloadUpdate');
                ipcRenderer.on('downloadProgress', (event, progressObj) => {
                    this.progress = JSON.stringify(progressObj);
                    this.downloadPercent = progressObj.percent.toFixed(0) || 0
                    if (progressObj.percent === 100) {
                        this.downloading = false;
                        // 询问是否立即更新
                        this.dialogUpdateNow = true
                    }
                })
            },
            saveVersionInfoList(updateInfo) {
                let versionInfoListOri = this.getVersionInfoList();
                versionInfoListOri.some((item, index, array) => {
                    // 判断是不是已经存在这个版本的信息,如果存在就删除它
                    if (updateInfo.version === item.version) {
                        array.splice(index, 1);
                        return true
                    }
                });
                // 将新的版本信息加入列表中
                versionInfoListOri.push(updateInfo);
                localStorage.setItem('versionInfoList', JSON.stringify(versionInfoListOri))
            },
            checkForUpdate() {
                // 开始检查
                ipcRenderer.send('checkForUpdate');
                // 添加自动更新事件的监听
                ipcRenderer.on('updateMessage', (event, obj) => {

                    //监测到新版本
                    if (obj.action === 'updateAva') {
                        this.hasNewVersion = true;
                        this.saveVersionInfoList(obj.updateInfo);
                        this.versionInfoList = this.getVersionInfoList()
                        //错误
                    } else if (obj.action === 'error') {
                        this.showError = true
                        // this.errorInfo = obj.errorInfo
                        this.errorInfo = '检测更新异常'
                        //现在使用的就是最新版本，不用下载
                    } else if (obj.action === 'updateNotAva') {
                        this.hasNewVersion = false
                        this.showError = true
                        this.errorInfo = '目前为最新版，不需要更新'
                    } else {
                        // console.log(text)
                    }
                })
            },
            updateNow() {
                // 立刻退出并更新
                ipcRenderer.send('isUpdateNow')
            }
        }
    }
</script>

<style scoped>

</style>
